package com.compass.mobile.ui.activity

import UserInfoManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.databinding.ActivityComplaintBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ifly.IFlyHelper
import com.compass.mobile.framework.ifly.IFlyOptCallback
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.models.AIMessageInfo
import com.compass.mobile.models.AiData
import com.compass.mobile.models.Dictionaries
import com.compass.mobile.models.SuggestMessageInfo
import com.compass.mobile.ui.adapter.SuggestAdapter
import com.compass.mobile.ui.adapter.SuggestMessageAdapter
import com.compass.mobile.ui.viewModel.IntelligentGuidanceViewModel
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import toBeanOrNull
import toJson

/**
 * Description： 投诉建议
 * Date:2024/6/20 10:30
 */
class ComplaintActivity : BaseVBActivity<ActivityComplaintBinding>() {

    private val intelligentGuidanceViewModel: IntelligentGuidanceViewModel by viewModels()

    private lateinit var suggestMessageAdapter: SuggestMessageAdapter//消息
    private lateinit var suggestTypeAdapter: SuggestAdapter//常见症状



    private var suggestMessageList: MutableList<SuggestMessageInfo> = mutableListOf()

    private var suggestType: String? = null

    private var list: MutableList<Dictionaries>? = null

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, ComplaintActivity::class.java)
            context.startActivity(intent)
        }
    }


    private var onBottomClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, id: String?) {
            if (codeType == 2) {
                id?.let {
                    DepartmentIntroductionActivity.start(
                        this@ComplaintActivity,
                        it, null,
                        "inquiry"
                    )
                }
            }
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        list = UserInfoManager.getSuggestTypeSource()?.toBeanOrNull<MutableList<Dictionaries>>()
        LogUtil.d("list==${list?.toJson()}")

        suggestMessageAdapter = SuggestMessageAdapter()
        suggestTypeAdapter = SuggestAdapter()
        mBinding.recyclerView.apply {
            layoutManager =
                LinearLayoutManager(
                    this@ComplaintActivity,
                    LinearLayoutManager.VERTICAL,
                    false
                )
            adapter = suggestMessageAdapter
        }
        suggestMessageAdapter.setBottomCallBack(onBottomClick)

        mBinding.edtKeyWords.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                val text = mBinding.edtKeyWords.text.toString().trim()
                sendMessage(text)
            }
            false
        }
        mBinding.rcyCommon.apply {
            val layoutFelManager = FlexboxLayoutManager(context)
            layoutFelManager.flexWrap = FlexWrap.WRAP // 按正常方向换行
            layoutFelManager.flexDirection = FlexDirection.ROW // 水平方向
            layoutFelManager.justifyContent = JustifyContent.FLEX_START // 左对齐
            layoutManager = layoutFelManager
            itemAnimator?.let {
                (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            }
            adapter = suggestTypeAdapter
        }
        suggestTypeAdapter.setData(list)

        suggestTypeAdapter.onItemClickListener = { _: View, p: Int ->
            val item = suggestTypeAdapter.getItem(p)
            suggestType = item?.value

            //清除之前选中的，然后添加
            if(list?.isNotEmpty() == true){
                for (item in list!!){
                    item.isSelect = false
                }
            }
            val isSelect  = item?.isSelect
            isSelect?.let { item?.isSelect = !it }
            suggestTypeAdapter.notifyDataSetChanged()
        }
        mBinding.edtKeyWords.requestFocus()
    }

    override fun initData() {
        intelligentGuidanceViewModel.getSuggestList()
        intelligentGuidanceViewModel.sendSuccessLiveData.observe(this) {
            it?.let {
                intelligentGuidanceViewModel.getSuggestList()
                mBinding.edtKeyWords.setText("")
            }
        }
        intelligentGuidanceViewModel.suggestMsgListLiveData.observe(this) {
            suggestMessageAdapter.setData(it)
            moveBottom()
        }

        GlobalScope.launch(Dispatchers.Main) {
            delay(1000)
            IFlyHelper.initIFly(this@ComplaintActivity,flyCallback)
        }


    }
    private val flyCallback = object : IFlyOptCallback {
        override fun onSuccess(text: String?) {
            IFlyHelper.getText(this@ComplaintActivity,textCallback)
//            mBinding.edtKeyWords.requestFocus()
        }

        override fun onFail(code: Int, text: String?) {
        }
    }
    private val textCallback = object : IFlyOptCallback {
        override fun onSuccess(text: String?){
            text.let {
                mBinding.edtKeyWords.setText(it)
                mBinding.edtKeyWords.text?.let { it1 -> mBinding.edtKeyWords.setSelection(it1.length) }
                mBinding.sendButton.requestFocus()
            }
        }

        override fun onFail(code: Int, text: String?) {
        }
    }
    override fun intListener() {
        mBinding.sendButton.onClick {
            val text = mBinding.edtKeyWords.text.toString().trim()
            sendMessage(text)
        }

    }


    /**
     * 发送消息并
     */
    private fun sendMessage(text: String) {
//        val text = "我的头痛，腹痛挂什么科室"
        if (text.isEmpty()) {
            showToast("请输入您的投诉或者建议")
            return
        }

//        aiMsg.add(SuggestMessageInfo(TYPE_TEXT, text, TYPE_SEND, null))//添加消息到adapter
//        suggestMessageAdapter.addItem(AIMessageInfo(TYPE_TEXT, text, TYPE_SEND, null))
//        mBinding.edtKeyWords.setText("")
        intelligentGuidanceViewModel.createSuggest(text, suggestType)

    }


    private fun moveBottom() {
        val position = suggestMessageAdapter.getData().size - 1
        mBinding.recyclerView.scrollToPosition(position)

    }

    override fun onDestroy() {
        super.onDestroy()
        IFlyHelper.unInitIFly()
    }

}